package com.k.kpp.web.controller;

import com.k.kc.util.FileUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author kivil
 */
@Controller
public class UploadController {

    private final static org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(UploadController.class);
    private final static long FILE_MAXSIZE= 10 * 1024 * 1024;

    @RequestMapping("/upload")
    public String uploadPage(){
        return "upload";
    }


    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "picName", required = true, dataType = "string", value = "群体主键", example = "1"),
            @ApiImplicitParam(paramType = "query", name = "picDesc", required = true, dataType = "string", value = "1:骨干人员 0:其他人员", example = "1"),
            @ApiImplicitParam(paramType = "file", name = "file", required = true, dataType = "MultipartFile", value = "文件") })
    @RequestMapping(value = "/uploadStrAndFile",method = RequestMethod.POST)
    @ResponseBody
    public String uploadStrAndFile(HttpServletRequest req){
        try{
            MultipartHttpServletRequest mReq = (MultipartHttpServletRequest)req;
            Map<String,MultipartFile> fileMap = mReq.getFileMap();
            String picName = mReq.getParameter("picName");
            String picDesc = mReq.getParameter("picDesc");
            MultipartFile file = fileMap.get("file0");
            String saveDir="";
            String saveName="";
            if(file != null){
                if(!checkFile(file)){
                    return "err:checkFile error";
                }
                saveDir = FileUtils.formatDir(getUploadDir());
                saveName = FileUtils.formatFilename(file.getOriginalFilename());
                saveFile(file,saveDir,saveName);
            }
            LOGGER.debug("picName:{} picDesc:{}",picName,picDesc);
            LOGGER.debug("saveDir:{} saveName:{}",saveDir,saveName);
            // save sql
            // save(picName,picDesc,saveDir,saveName);
            return "SUCCESS";
        }catch (IOException e) {
            LOGGER.error("ERROR:",e);
            return "ERROR:"+e.getMessage();
        } catch (Exception e1){
            LOGGER.error("ERROR:",e1);
            return "ERROR"+e1.getMessage();
        }
    }
    private String getUploadDir(){
        return "/home/upload";
    }

    private boolean checkFile(MultipartFile file){
        return file != null && !file.isEmpty() && file.getSize()>0 && file.getSize() <= FILE_MAXSIZE;
    }

    /**
     * save file
     * @param file file
     * @param saveDir saveDir:
     * @param saveName  fileName:eg:flower.jpg
     * @throws IOException e
     */
    private void saveFile(MultipartFile file,String saveDir,String saveName) throws IOException {
        String filePath = saveDir + saveName;
        File f = new File(saveDir);
        if(!f.exists()){
            LOGGER.warn("upload dir not found create:"+saveDir);
            boolean isMkdirs = f.mkdirs();
            if(!isMkdirs){
                throw new IllegalArgumentException("upload dir create error for dir:"+saveDir);
            }
            file.transferTo(new File(filePath));
        }
    }
}
